﻿using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class MenusPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IMenusView _view;
        public IDiskAccess DiskAccess;

        public MenusPresenter(IMenusView view)
            : this(view, new RepositoryFactory())
        {
            DiskAccess = new DiskAccess();
        }

        public MenusPresenter(IMenusView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.Menus)
                _view.RedirectToPermissionDeniedPage();
        }
        
        public void Initialize()
        {
            SetMenus();
        }
        
        public void SetMenus()
        {
            _view.SetMenus(_administrator.CurrentSite.Menus);
        }
        
        public void DeleteMenu(int id)
        {
            Menu menu = SiteRepository.GetMenu(id, _administrator.CurrentSite.ID);
            if (true) //TODO: Check if menu is in use
                PerformDelete(menu);
            //else
            //_view.DisplayUnableToDeleteAlert(menu.Name);
        }
        
        private void PerformDelete(Menu menu)
        {
            menu.Site.Menus.Remove(menu);
            menu.Site = null;
            while (menu.Versions.Count > 0)
            {
                menu.Versions[0].Parent = null;
                menu.Versions.RemoveAt(0);
            }
            SiteRepository.DeleteMenu(menu);
            SiteRepository.SaveSite(_administrator.CurrentSite);
            SetMenus();
        }

        public int CopyMenu(int id)
        {
            Menu original = SiteRepository.GetMenu(id, _administrator.CurrentSite.ID);
            if (original == null)
                return -1;
            var clone = (Menu)original.Clone();
            SiteRepository.SaveMenu(clone);
            clone.StyleSheet.CurrentVersion.Code = clone.StyleSheet.CurrentVersion.Code.Replace(
                ".cmsMenu" + original.ID, ".cmsMenu" + clone.ID);
            SiteRepository.SaveMenu(clone);
            DiskAccess.DeleteFile("__System\\Menus\\" + clone.ID + ".css");
            DiskAccess.CreateTextFile("__System\\Menus\\" + clone.ID + ".css", clone.StyleSheet.CurrentVersion.Code);
            return clone.ID;
        }
    }
}